<?php

// $Id$

require_once($WSC->get_site_inc_dir().'modules/tangra_cms/_sys/tcms_admin_web_page_wed_ua.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/category/tcms_category_dbc.class.php');


class Categories_WP extends TCMS_Admin_Web_Page_WED_UA {
	public function create_view($name = 'default') {
		$ret = new TCMS_Admin_Page_View($this, $name, 'modules/tangra_cms/pages/_category/');

		return $ret;
	}


	public function init() {
		parent::init();

		$v = $this->create_view();
		$this->add_view($v);

		$parent_category_event = new Web_Event_Simple_Int('parent_category', Tangra_Parameter_Method::GET, 'parent_category');
		$this->wed->add_wed_event_action_pair($parent_category_event, 'parent_category_event', 30);

		$move_up_event = new Web_Event_Simple_Int('move_up', Tangra_Parameter_Method::GET, 'move_up');
		$move_up_event_comp = new Web_Event_Composite('move_up_event_comp');
		$move_up_event_comp->add_wes($move_up_event);
		$move_up_event_comp->add_wes($parent_category_event);
		$this->wed->add_wed_event_action_pair($move_up_event_comp, 'move_up_event', 10);

		$move_down_event = new Web_Event_Simple_Int('move_down', Tangra_Parameter_Method::GET, 'move_down');
		$move_down_event_comp = new Web_Event_Composite('move_down_event_comp');
		$move_down_event_comp->add_wes($move_down_event);
		$move_down_event_comp->add_wes($parent_category_event);
		$this->wed->add_wed_event_action_pair($move_down_event_comp, 'move_down_event', 20);
	}


	protected function parent_category_event($parent_category) {
		$dbc = $this->get_dbc();

		$this->export('parent_category_id', $parent_category);

		$parent_category_obj = new TCMS_Category_DBC();
		if ($parent_category != 0) {
			if ($parent_category_obj->load_by_id($dbc, $parent_category)) {
				$this->export('parent_category_title', $parent_category_obj->get_title());
			}
		}

		$categories = TCMS_Category_DBC::load_categories_by_parent($dbc, $parent_category);

		$this->export('categories', $categories);

		$view = $this->get_view('default');

		return $view;
	}


	protected function move_up_event($params) {
		$dbc = $this->get_dbc();
		try {
			$dbc->start_trans();
			TCMS_Category_DBC::move_up($dbc, $params['move_up']);
			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}

		return $this->parent_category_event($params['parent_category']);
	}


	protected function move_down_event($params) {
		$dbc = $this->get_dbc();
		try {
			$dbc->start_trans();
			TCMS_Category_DBC::move_down($dbc, $params['move_down']);
			$dbc->complete_trans();
		} catch (Exception $e) {
			$dbc->fail_trans();
			$dbc->complete_trans();
			throw $e;
		}

		return $this->parent_category_event($params['parent_category']);
	}


	protected function default_event() {
		throw new Tangra_Module_Exception('Expecting parent_category parameter.');
	}
}


